package lenovo.agriculture.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

/**
 * 本类是显示Splash界面的控制类
 * 
 * @author asus
 */

public class SplashActivity extends BaseActivity {
	private static final int ENTER_HOME = 0x00;
	private static final int ENTER_SPLASH = 0x01;
	private static final String FILE_NAME = "first";
	private int waitTime = 3 * 1000;
	private TextView mSoftwareVersionTV;
	private SharedPreferences mPrefrence;
	private Handler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);
		getPreferences();
		handleMessage();
		initView();
		setText();
		into();
	}

	/**
	 * 消息处理
	 * 
	 */
	private void handleMessage() {
		mHandler = new Handler(new Handler.Callback() {

			@Override
			public boolean handleMessage(Message msg) {
				if (msg.what == ENTER_HOME) {
					// 进入主页面
					Intent mHomeIntent = new Intent(SplashActivity.this,
							MainActivity.class);
					startActivity(mHomeIntent);
				} else {
					// 将App启动的值设为false
					Editor mEditor = mPrefrence.edit();
					mEditor.putBoolean("isFirst", false);
					mEditor.commit();
					// 进入引导界面
					Intent mSplshIntent = new Intent(SplashActivity.this,
							GuideActivity.class);
					startActivity(mSplshIntent);
				}
				finish();
				return false;
			}
		});
	}

	/**
	 * 控制跳转
	 */
	private void into() {
		if (isFirstRun()) {
			mHandler.sendEmptyMessageDelayed(ENTER_SPLASH, waitTime);
		} else {
			mHandler.sendEmptyMessageDelayed(ENTER_HOME, waitTime);
		}
	}

	/**
	 * 给TextView设值
	 */
	private void setText() {
		mSoftwareVersionTV.setText(getString(R.string.software_version)
				+ getVersion());
	}

	/**
	 * 初始化TextView
	 */
	private void initView() {
		mSoftwareVersionTV = (TextView) findViewById(R.id.software_version_tv);
	}

	/**
	 * 得到SharedPreferences
	 */
	private void getPreferences() {
		mPrefrence = getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
	}

	/**
	 * 判断程序是否是第一次运行
	 * 
	 * @return 是否第一次运行
	 */
	private boolean isFirstRun() {
		return mPrefrence.getBoolean("isFirst", true);
	}

	/**
	 * 获取程序的版本号
	 * 
	 * @return 程序版本号
	 */
	private String getVersion() {
		String versionString = null;
		try {
			PackageManager manager = getPackageManager();
			PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
			versionString = info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionString;
	}
}
